package thread;


import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;
    private Runnable runnable;

    public MyTimerTask(Runnable runnable, long time) {
        this.time = time + System.currentTimeMillis();
        this.runnable = runnable;
    }

    public long getTime() {
        return time;
    }
    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return Long.compare(time, o.time);
    }
}
class MyTimer{
    private PriorityQueue<MyTimerTask> tasks = new PriorityQueue<>();

    public void schedule(Runnable runnable, long delay) {
        synchronized (this) {
            tasks.add(new MyTimerTask(runnable, delay));
            this.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread(() -> {
            while (true){
                synchronized (this) {
                    while (tasks.isEmpty()) {
                        try {
                            this.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task = tasks.peek();
                    if  (task.getTime() <= System.currentTimeMillis()){
                        task.getRunnable().run();
                        tasks.poll();
                    }else{
                        try {
                            this.wait(task.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        thread.start();
    }
}
public class Demo26 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序开始执行");
    }
}
